<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { BusChangeLogVO } from '#/api/register/bus/log/model';

import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { Page } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';

import { message, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { changeLogPage, changeLogSetReadStatus } from '#/api/register/bus/log';
import { taskInfo } from '#/api/register/bus/task';

import { columns, querySchema } from './log';

const route = useRoute();
const router = useRouter();
const taskName = ref<string>();

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 90,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    // trigger: 'row',
  },
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        return await changeLogPage({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
          taskId: route.query.taskId,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'bus-change-log-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

async function handleRead(row: BusChangeLogVO) {
  await changeLogSetReadStatus({ id: row.id });
  await tableApi.query();
}

const { setTabTitle } = useTabs();
onMounted(async () => {
  const task = await taskInfo(route.query.taskId as string);
  if (task) {
    tableApi?.formApi.updateSchema([
      {
        fieldName: 'groupId',
        componentProps: {
          exhibitionId: task.exhibitionId,
        },
      },
    ]);
    taskName.value = `${task.name}`;
    setTabTitle(`巴士任务变更记录：${task.name}`);
  } else {
    message.warning('查无此巴士任务');
    await router.replace('/register/busTask');
  }
});
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable>
      <template #table-title>
        <main-title text="团体巴士任务变更记录" />
      </template>
      <template #toolbar-tools></template>
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-if="row.readStatus === 0"
            @click.stop="handleRead(row)"
          >
            标记为已读
          </ghost-button>
          <span v-else class="text-[#909399]">已读</span>
        </Space>
      </template>
    </BasicTable>
  </Page>
</template>
